package com.ruoyi.supermarket.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.supermarket.domain.*;
import com.ruoyi.supermarket.domain.Vo.ShCx;
import com.ruoyi.supermarket.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.ruoyi.supermarket.service.IPurchaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购采退汇总Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-22
 */
@Service
public class PurchaseServiceImpl implements IPurchaseService 
{
    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private XqpurchaseMapper xqpurchaseMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private YfpayMapper yfpayMapper;

    @Autowired
    private XqyfpayMapper xqyfpayMapper;

    @Autowired
    private QkMapper qkMapper;
    /**
     * 查询采购采退汇总
     * 
     * @param purchaseId 采购采退汇总主键
     * @return 采购采退汇总
     */
    @Override
    public Purchase selectPurchaseByPurchaseId(Long purchaseId)
    {
        return purchaseMapper.selectPurchaseByPurchaseId(purchaseId);
    }

    /**
     * 查询采购采退汇总列表
     * 
     * @param purchase 采购采退汇总
     * @return 采购采退汇总
     */
    @Override
    public List<Purchase> selectPurchaseList(Purchase purchase)
    {
        List<String> list = new ArrayList<String>();
        list.add("0");
        list.add("2");
        list.add("4");
        purchase.setIsRkList(list);
        return purchaseMapper.selectPurchaseList(purchase);
    }

    /**
     * 新增采购采退汇总
     * 
     * @param purchase 采购采退汇总
     * @return 结果
     */
    @Override
    public int insertPurchase(Purchase purchase)
    {
        purchase.setCreateTime(LocalDateTime.now());
        return purchaseMapper.insertPurchase(purchase);
    }

    /**
     * 修改采购采退汇总
     * 
     * @param purchase 采购采退汇总
     * @return 结果
     */
    @Override
    public int updatePurchase(Purchase purchase)
    {
        purchase.setIsSh("1");
        return purchaseMapper.updatePurchase(purchase);
    }

    /**
     * 批量删除采购采退汇总
     * 
     * @param purchaseIds 需要删除的采购采退汇总主键
     * @return 结果
     */
    @Override
    public int deletePurchaseByPurchaseIds(Long[] purchaseIds)
    {
        return purchaseMapper.deletePurchaseByPurchaseIds(purchaseIds);
    }

    /**
     * 删除采购采退汇总信息
     * 
     * @param purchaseId 采购采退汇总主键
     * @return 结果
     */
    @Override
    public int deletePurchaseByPurchaseId(Long purchaseId)
    {
        return purchaseMapper.deletePurchaseByPurchaseId(purchaseId);
    }

    @Override
    @Transactional
    public AjaxResult cgrk(RkVo rkVo) {
        //改采购详情状态入库
        Xqpurchase xqpurchase = xqpurchaseMapper.selectXqpurchaseByPId(rkVo.getPId());
        xqpurchase.setIsRk("1");
        xqpurchaseMapper.updateXqpurchase(xqpurchase);

        Xqpurchase x1 = new Xqpurchase();
        x1.setPurchaseId(rkVo.getPurchaseId());
        //改汇总表入库状态
        List<Xqpurchase> list = xqpurchaseMapper.selectXqpurchaseList(x1);
        int flag = 0;
        for (Xqpurchase xflag : list) {
            if (xflag.getIsRk().equals("0")) {
                flag = 1;
                break;
            }
        }
        Purchase p = new Purchase();
        //表示这个采购单全部入库
        p.setPurchaseId(rkVo.getPurchaseId());
        if(flag == 0){
            p.setIsRk("1");
        }else{
            p.setIsRk("4");
        }
        purchaseMapper.updatePurchase(p);

        //插如库存表
        Xqpurchase  xrk = xqpurchaseMapper.selectXqpurchaseByPId(rkVo.getPId());
        //更改钱
        Purchase purchase = purchaseMapper.selectPurchaseByPurchaseId(rkVo.getPurchaseId());
        Qk qk = qkMapper.selectBySupplyId(purchase.getSupplyId());
        qk.setQkPrice(qk.getQkPrice().add(xrk.getZprice()));
        qkMapper.update(qk);
        //商品id，货位，单价 不一致就插入，进行批次管理
        Stock s = new Stock();
        s.setWhId(rkVo.getWhId());
        s.setProductId(xrk.getProductId());
        s.setCjPrice(xrk.getPrice());
        Stock stocks = stockMapper.selectStockByProductId(s);

        if(stocks != null){
            //修改数量，总金额，赠品数量
            //数量
            stocks.setStockNum(stocks.getStockNum() + xrk.getSum());
            //总金额
            stocks.setStockPrice(stocks.getStockPrice().add(xrk.getZprice()));

            //赠品数量
            stocks.setStockZpNum(stocks.getStockZpNum());

            stockMapper.updateStock(stocks);

            return AjaxResult.success();
        }else{
            //插入
            Stock stock = Stock.builder()
                    .productId(xrk.getProductId())
                    .whId(rkVo.getWhId())
                    .stockNum(xrk.getSum())
                    .stockPrice(xrk.getZprice())
                    .cjPrice(xrk.getPrice())
                    .build();
            stockMapper.insertStock(stock);
            Long stockId = stock.getStockId();

            //生成批次号
            SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
            String dateTime = dateFormat.format(new Date());
            stock.setBatch("PC_"+dateTime +"_"+stockId);
            stockMapper.updateStock(stock);
            return AjaxResult.success();
        }
    }

    @Override
    public AjaxResult audit(ShCx shCx) {
        Purchase purchase = purchaseMapper.selectPurchaseByPurchaseId(shCx.getPurchaseId());
        purchase.setIsSh(shCx.getIsSh());
        purchase.setShName(SecurityUtils.getLoginUser().getUsername());
        purchase.setShTime(LocalDateTime.now());
        purchase.setShRemark(shCx.getShRemark());
        purchaseMapper.updatePurchase(purchase);
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult outStore(Long purchaseId) {
        //改汇总表状态
        Purchase purchase = purchaseMapper.selectPurchaseByPurchaseId(purchaseId);
        purchase.setIsRk("3");
        purchaseMapper.updatePurchase(purchase);
        Xqpurchase x = new Xqpurchase();
        x.setPurchaseId(purchaseId);
        List<Xqpurchase> list = xqpurchaseMapper.selectXqpurchaseList(x);
        for (Xqpurchase xqpurchase : list) {
           Stock stock =  stockMapper.selectStockBatch(xqpurchase.getBatch());
            Purchase p = purchaseMapper.selectPurchaseByPurchaseId(purchaseId);
            Qk qk = qkMapper.selectBySupplyId(p.getSupplyId());
            qk.setQkPrice(qk.getQkPrice().add(xqpurchase.getZprice()));
            qkMapper.update(qk);
           stock.setStockNum(stock.getStockNum() + xqpurchase.getSum());
           stock.setStockPrice(stock.getStockPrice().add(stock.getCjPrice().multiply(BigDecimal.valueOf(xqpurchase.getSum()))));
           stockMapper.updateStock(stock);
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult pay(List<Long> ids) {
        //只能是同一个供应商来做应付款
        Long supplyId = purchaseMapper.selectPurchaseByPurchaseId(ids.get(0)).getSupplyId();
        Long z_sum = 0L;
        BigDecimal z_price = BigDecimal.ZERO;
        for (Long id : ids) {
            Purchase purchase = purchaseMapper.selectPurchaseByPurchaseId(id);
            purchase.setIsZd("1");
            purchaseMapper.updatePurchase(purchase);
            z_sum += purchase.getZnum();
            z_price = z_price.add(purchase.getZprice());
        }
        //插入汇总
        Yfpay yfpay = new Yfpay();
        yfpay.setSupplyId(supplyId);
        yfpay.setZsum(z_sum);
        yfpay.setZprice(z_price);
        yfpay.setCreateTime(LocalDateTime.now());
        yfpay.setCreateName(SecurityUtils.getLoginUser().getUsername());
        yfpay.setIsSh("1");
        yfpay.setIsHx("0");
        yfpayMapper.insertYfpay(yfpay);
        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
        String dateTime = dateFormat.format(new Date());
        Long yfId = yfpay.getYfpayId();
        yfpay.setYfCode("YF_"+dateTime +"_"+yfId);
        yfpayMapper.updateYfpay(yfpay);

        //插入详情
        for (Long id : ids) {
            Xqpurchase xqpurchase =new  Xqpurchase();
            xqpurchase.setPurchaseId(id);
            List<Xqpurchase> list = xqpurchaseMapper.selectXqpurchaseList(xqpurchase);
            for (Xqpurchase x : list) {
                Xqyfpay xqyfpay =new Xqyfpay();
                xqyfpay.setYspayId(yfId);
                xqyfpay.setpId(x.getpId());
                xqyfpayMapper.insertXqyfpay(xqyfpay);
            }
        }
        return AjaxResult.success(yfpay.getYfCode());
    }

    @Override
    public List<Purchase> selectPurchaseListTwo(Purchase purchase) {
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("3");
        purchase.setIsRkList(list);
        purchase.setIsZd("0");
        return purchaseMapper.selectPurchaseList(purchase);
    }

    @Override
    public List<Purchase> selectPurchaseListThree(Purchase purchase) {
        List<String> list = new ArrayList<String>();
        list.add("0");
        list.add("2");
        purchase.setIsRkList(list);
        return purchaseMapper.selectPurchaseList(purchase);
    }

    @Override
    public List<Purchase> selectPurchaseListZf(Purchase purchase) {
        List<String> list = new ArrayList<String>();
        list.add("0");
        list.add("2");
        purchase.setIsRkList(list);
        List<String> listSh = new ArrayList<String>();
        listSh.add("1");
        listSh.add("2");
        purchase.setIsShList(listSh);
        return purchaseMapper.selectPurchaseListZf(purchase);
    }

    @Override
    public AjaxResult zfPurchasepay(Long id) {
        purchaseMapper.deletePurchaseByPurchaseId(id);
        xqpurchaseMapper.deleteXqpurchaseByPurchaseId(id);
        return AjaxResult.success();
    }

    @Override
    public List<Purchase> selectPurchasecSList(Purchase purchase) {
        return purchaseMapper.selectPurchaseList(purchase);
    }
}
